// components/my-dialog/my-dialog.js
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean,
      vlaue: false
    },
    addRouter: {
      type: String,
      vlaue: ''
    },
    showUser: false,
  },

  /**
   * 组件的初始数据
   */
  data: {
    adminArr: [],
    subAdminArr: [],
    isAgreed: false,
    avatarUrl: '',
    nickName: '',
    nickDisabled: false
  },

  ready() {
    this.getAdmin();
    this.setData({
      avatarUrl: wx.getStorageSync('headPortrait'),
      nickName: wx.getStorageSync('nickName'),
    });
  },
  /**
   * 组件的方法列表
   */
  methods: {
    reset() {
      this.setData({
        avatarUrl: wx.getStorageSync('headPortrait'),
        nickName: wx.getStorageSync('nickName'),
      });
    },
    getAdmin() {
      wx.request({
        url: `${app.globalData.baseUrl}/api/accounting/selManage`,
        method: "GET",
        header: {
          'token': wx.getStorageSync('token'),
          "Content-Type": "application/json"
        },
        success: (res) => {
          if (res.data.code == 0) {
            const arr = [];
            const subArr = [];
            res.data.data?.forEach(item => {
              if (item.status === '1') arr.push(item.tel);
              if (item.status === '0') subArr.push(item.tel);
            });
            this.setData({ adminArr: arr, subAdminArr: subArr });
          } else {
            wx.showToast({
              title: res.data.msg || '出错啦！',
              icon: 'error',
              duration: 2000
            })
          }
        }
      })
    },
    // 同意复选框点击事件
    onAgreeClick() {
      this.setData({
        isAgreed: !this.data.isAgreed
      })
    },
    linkPrivacyPolicy() {
      wx.navigateTo({
        url: '/pages/privacyPolicy/index',
      })
    },
    showAgree() {
      wx.showToast({
        title: '请先阅读并同意隐私权保护政策',
        icon: 'none'
      });
    },
    getPhoneNumber(e) {
      const _that = this;
      if (e.detail.errMsg === "getPhoneNumber:ok") {
        wx.request({
          method: 'POST',
          data: {
            code: e.detail.code
          },
          header: {
            "Content-Type": "application/json",
            'token': wx.getStorageSync('token'),
          },
          url: `${app.globalData.baseUrl}/api/login/auth/phone`,
          success: res => {
            if (res.data.code == 0) {
              _that.login(res.data?.data?.phone?.phoneNumber);
            } else {
              wx.showModal({
                title: '提示',
                content: res.data.msg || '获取失败！',
                showCancel: false,
                success: function (res) {
                  _that.setPhoneShow(1);
                }
              })
            }
          },
          fail: () => {
            wx.showModal({
              title: '提示',
              content: '获取失败！',
              showCancel: false,
              success: function (res) {
                _that.setPhoneShow();
              }
            })
          }
        })
      } else {
        _that.setPhoneShow();
      }
    },

    login(tel) {
      wx.setStorageSync('userPhone', tel);
      if (this.data.subAdminArr.indexOf(tel.toString()) > -1) {
        wx.setStorageSync('subAdmin', 1);
      } else {
        wx.setStorageSync('subAdmin', 0);
      };
      if (this.data.adminArr.indexOf(tel.toString()) > -1) {
        wx.setStorageSync('admin', 1);
      } else {
        wx.setStorageSync('admin', 0);
      };
      this.setPhoneShow(1);
    },

    setPhoneShow(val) {
      this.triggerEvent("closeLogin", val === 1);
      this.setData({ isAgreed: false });
      if (!this.properties.addRouter) {
        wx.switchTab({
          url: '/pages/index/index',
        });
      }
    },
    onChooseAvatar(e) {
      const { avatarUrl } = e.detail;
      const _that = this;
      wx.showToast({
        title: '正在上传...',
        icon: 'loading',
        mask: true,
        duration: 1000
      });
      wx.uploadFile({
        url: `${app.globalData.baseUrl}/common/upload`,
        filePath: avatarUrl,
        name: 'file',
        formData: {
          'user': 'test'
        },
        success: function (res) {
          const datas = JSON.parse(res.data);
          _that.setData({
            avatarUrl: datas.url,
          })
          wx.showToast({
            title: '图片上传成功',
            icon: 'loading',
            showCancel: false,
            duration: 1000
          })
        },
        fail: function (res) {
          wx.hideToast();
          wx.showModal({
            title: '错误提示',
            content: '上传图片失败',
            showCancel: false,
            success: function (res) { }
          })
        }
      });
    },
    bindinput(e) {
      const { value } = e.detail;
      this.setData({ nickName: value })
    },
    nickBlur(e) {
      const { value } = e.detail;
      this.setData({ nickName: value, nickDisabled: false });
    },
    nickfocus() {
      this.setData({ nickDisabled: true });
    },
    formSubmit() {
      if (this.nickDisabled) return;
      wx.showLoading()
      wx.request({
        url: `${app.globalData.baseUrl}/api/login/registers`,
        method: "POST",
        data: {
          nickName: this.data.nickName,
          headPortrait: this.data.avatarUrl,
          openId: wx.getStorageSync('openId'),
        },
        header: {
          "Content-Type": "application/json"
        },
        success: (res) => {
          if (res.data.code == 0) {
            wx.setStorageSync('headPortrait', this.data.avatarUrl || headPortrait);
            wx.setStorageSync('nickName', this.data.nickName || nickName);
            wx.setStorageSync('token', res.data.data.token);
            wx.setStorageSync('userId', res.data.data.user.id);
            this.triggerEvent("closeUser");
          } else {
            wx.showToast({
              title: '系统错误',
            })
          }
        },
        complete: () => {
          this.triggerEvent("closeUser");
          wx.hideLoading();
        }
      })
    },
    closeUser() {
      this.triggerEvent("closeUser");
    }
  }
})
